package cn.com.onlinetool.jt809.handler;

import cn.com.onlinetool.jt809.bean.Message;
import cn.com.onlinetool.jt809.bean.UpConnectReq;
import cn.com.onlinetool.jt809.constants.JT809DataTypeConstants;
import cn.com.onlinetool.jt809.constants.JT809ResCodeConstants;
import cn.com.onlinetool.jt809.manage.TcpChannelMsgManage;
import cn.com.onlinetool.jt809.mapper.SysJt809UserConfigMapper;
import cn.com.onlinetool.jt809.pojo.SysJt809UserConfig;
import cn.com.onlinetool.jt809.util.ByteArrayUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author choice
 * 主链路登陆逻辑处理
 * @date 2019-06-28 14:35
 */
@Slf4j
@Component
public class UpConnectHandler implements CommonHandler {
    public final static String KEY = "jt809:sys:user:config:";
    @Resource
    TcpChannelMsgManage channelMsgManage;
    @Autowired
    private SysJt809UserConfigMapper sysJt809UserConfigMapper;
    @Autowired
    private RedisTemplate redisTemplate;

//    @Autowired
//    KafkaTemplate<String,Object> kafkaTemplate;
//    @Autowired
//    TcpChannelMsgManage tcpChannelMsgManage;

    @Override
    public void handler(ChannelHandlerContext ctx, Message msg) {
        this.login(ctx, msg);
    }

    /**
     * 登陆逻辑处理
     *
     * @param msg
     */
    private void login(ChannelHandlerContext ctx, Message msg) {
        int index = 0;
        int userId = ByteArrayUtil.bytes2int(ByteArrayUtil.subBytes(msg.getMsgBody(), index, 4));
        index += 4;
        String password = ByteArrayUtil.bytes2gbkString(ByteArrayUtil.subBytes(msg.getMsgBody(), index, 8));
        password = password.replaceAll("\\u0000", "");
        index += 8;
        String downLinkIp = ByteArrayUtil.bytes2gbkString(ByteArrayUtil.subBytes(msg.getMsgBody(), index, 32));
        downLinkIp = downLinkIp.replaceAll("\\u0000", "");
        index += 32;
        int downLinkPort = ByteArrayUtil.bytes2int(ByteArrayUtil.subBytes(msg.getMsgBody(), index, 2));
        index += 2;

        UpConnectReq req = new UpConnectReq();
        req.setUserId(userId);
        req.setPassword(password);
        req.setDownLinkIp(downLinkIp);
        req.setDownLinkPort(downLinkPort);
        log.info("登陆请求信息：" + JSONObject.toJSONString(req));

        byte[] result = new byte[]{JT809ResCodeConstants.UpConnect.SUCCESS};
        byte[] verifyCode = new byte[4];
        msg.getMsgHead().setMsgId((short) JT809DataTypeConstants.UP_CONNECT_RSP);
        //根据用户id查询配置
        HashOperations hashOperations = redisTemplate.opsForHash();
        String configStr = (String) hashOperations.get(KEY, String.valueOf(userId));
        SysJt809UserConfig config = JSON.parseObject(configStr, SysJt809UserConfig.class);//(SysJt809UserConfig) hashOperations.get(KEY, String.valueOf(userId));

        if (config == null) {
            log.info("用户没有注册");
            result = new byte[]{JT809ResCodeConstants.UpConnect.USER_NOT_EXIST};
        } else {
//            if (!config.getDownLinkIp().equals(req.getDownLinkIp())) {
//                log.info("ip地址不正确");
//                result = new byte[]{JT809ResCodeConstants.UpConnect.IP_ERROR};
//            } else
            if (config.getMsgGnssCenterId() != msg.getMsgHead().getMsgGnssCenterId()) {
                log.info("接入码不正确");
                result = new byte[]{JT809ResCodeConstants.UpConnect.GUSSCENTERID_ERROR};
            } else if (config.getUserId().intValue() != req.getUserId()) {
                log.info("用户没有注册");
                result = new byte[]{JT809ResCodeConstants.UpConnect.USER_NOT_EXIST};
            } else if (!config.getPassword().equals(password)) {
                log.info("密码错误");
                result = new byte[]{JT809ResCodeConstants.UpConnect.PASSWORD_ERROR};
            } else {
                log.info("登陆成功");
                byte[] body = ByteArrayUtil.append(result, verifyCode);
                msg.getMsgHead().setMsgLength(msg.getMsgHead().getMsgLength() - msg.getMsgBody().length + body.length);
                msg.setMsgBody(body);
                ctx.write(msg);
                channelMsgManage.addChannel(Integer.toString(config.getUserId()), ctx.channel());
                return;
            }
        }

        byte[] body = ByteArrayUtil.append(result, verifyCode);
        msg.getMsgHead().setMsgLength(msg.getMsgHead().getMsgLength() - msg.getMsgBody().length + body.length);
        msg.setMsgBody(body);
        ctx.write(msg);
        ctx.channel().close();
    }
}
